
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/C.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/network/response/ResourceResp.dart';
import 'package:huajianshe_app/pages/circle/LinkCirclesPage.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/utils/Device.dart';
import 'package:huajianshe_app/utils/KeyboardUtil.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/BadgeWidget.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'package:huajianshe_app/widget/dialog/SelectMediaBottomSheet.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'PrePostPage.dart';

class PostPage extends StatefulWidget {

  final int postType;
  final List<SimpleCircleInfo>? joined;
  final List<SimpleCircleInfo>? created;

  const PostPage(this.postType, this.joined, this.created, {
    Key? key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PostPageState();
  }
}

class _PostPageState extends BaseState<PostPage> {
  final contentController = TextEditingController();
  final contentNode = FocusNode();
  bool keyboardShown = false;
  List<String> images = [];
  List<MediaFileInfo> mediaInfos = [];
  final _picker = ImagePicker();
  List<SelectedCircle>? selected;

  @override
  Widget build(BuildContext context) {
    keyboardShown = KeyboardUtil.isKeyboardShown(context);
    print('${widget.joined?.length}${widget.created?.length}');
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CAppBar(bgColor: C.grayF6, title: widget.postType == PostType.MOMENT ? '发布动态' : '发布商机', actions: [
        SmartButton(width: 50, height: 24, fontSize: 15, textColor: Colors.white, text: '发布', radius: 12, onPressed: publish,)
      ]),
      body: SimpleScrollView(
        children: [
          TextField(
            controller: contentController,
            focusNode: contentNode,
            maxLength: 240,
            keyboardType: TextInputType.multiline,
            maxLines: 12,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                border: UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
                enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
                focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
                // labelText: '内容(240字)',
                hintText: '发布你此刻的心情商机/工作思考/行业观察(240字)',
                hintStyle: TS(15, C.gray999),
            ),
          ),
          H(10),
        ],
        bottomView: buildBottom(),
      ),
    );
  }

  Widget buildMedia() {
    return Row(mainAxisSize: MainAxisSize.min, children: [
      W(15),
      ...mediaInfos.map((info) {
        var index = mediaInfos.indexOf(info);
        Widget media = LoadImage(info.path, width: 70, height: 70);
        if (info.isVideo) {
          media = Stack(children: [
            media,
            Positioned.fill(child: Center(child: LoadImage('play_20')))
          ]);
        }
        return Row(mainAxisSize: MainAxisSize.min, children: [
          BadgeWidget(width: 77, height: 77, widget: media,
            // Semantics(
            //   child: Image.file(File(mediaInfos[index].path), width: 70, height: 70, fit: BoxFit.cover),
            //   label: 'image_picker_example_picked_image'),
            badget: GestureDetector(onTap: () {
              setState(() { mediaInfos.removeAt(index); });
            }, child: LoadImage('ic_delete_media')),
          ),
          W(10)
        ]);

      }).toList(),
      if (mediaInfos.length == 0 || (!mediaInfos[0].isVideo && mediaInfos.length < 3))
        GestureDetector(onTap: showMediaDialog, child: LoadImage('ic_upload_media'),)

    ]);
  }

  Widget buildCircles() {
    if (selected?.isNotEmpty == true) {
      return Padding(padding: EdgeInsets.symmetric(horizontal: 10), child: Wrap(spacing: 10, runSpacing: 10, children: [
        ...selected!.map((e) {
          return RoundedCornerWidget(
              child: Text('#${e.circle.title}', style: TS(14, C.gray0D0E15),), height: 32, radius: 16, borderWidth: 0,
                  backgroundColor: C.grayF6, padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6)
          );
        })
      ]));
    }
    return H(0);
  }

  Widget buildBottom() {
    return
      Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
        buildCircles(),
        H(10),
        buildMedia(),
        H(10),
        Row(mainAxisSize: MainAxisSize.max, children: [
          W(10),
          GestureDetector(onTap: () { linkCircles(context); }, child:
            RoundedCornerWidget(child: Row(mainAxisSize: MainAxisSize.min, children: [
              W(10),
              LoadImage('ic_contacts'),
              W(10),
              Text('关联圈子', style: TS(15, Colors.black),),
              W(10),
              LoadImage('ic_add'),
              W(10),
            ],), backgroundColor: C.grayF6, height: 28, radius: 14,)
          ),
          Spacer(),
          if (keyboardShown && Device.isIOS) GestureDetector(onTap: () { FocusScope.of(context).unfocus(); }, child: Icon(Icons.arrow_drop_down)),
          // TextButton(onPressed: null, child: Text('发布'))
        ]),
        H(10)
      ]);
  }

  void showMediaDialog() {
    DialogUtil.showBottomDialogV2(context, SelectMediaBottomSheet(
      includeVideo: mediaInfos.length == 0,
      onMediaResult: (isVideo, isCamera) {
        onMediaResult(isVideo, isCamera);
      },
    ), radius: 13, margin: EdgeInsets.symmetric(horizontal: 5));
  }

  void onMediaResult(bool isVideo, isCamera) async {
    var source = isCamera ? ImageSource.camera : ImageSource.gallery;
    if (isVideo) {
      final PickedFile? pickedFile = await _picker.getVideo(
          source: source, maxDuration: const Duration(seconds: 15));
      if (pickedFile != null) {
        File file = File(pickedFile.path);
        print('${file.path}');
        VideoPlayerController controller = new VideoPlayerController.file(file);
        await controller.initialize();
        Duration d = controller.value.duration;
        int seconds = d.inSeconds;
        if (seconds > 15) {
          Toast.show('视频长度限制为15秒');
          return;
        }
        uploadVideo(file);
      }
    } else {
      final pickedFile = await _picker.getImage(source: source);
      if (pickedFile != null) {
        File file = File(pickedFile.path);
        uploadImage(file);
      }
    }
  }

  void linkCircles(BuildContext context) {
    AppNavigator.push(context, RouteName.LINK_CIRCLES,
        arguments: {'joined': widget.joined, 'created': widget.created, 'selected': selected},
        onPageResult: (v) {
          this.selected = v;
          setState(() => {});
        });
  }

  publish() {
    String text = contentController.text;
    if (text.isEmpty) {
      return;
    }
    if (selected?.isNotEmpty == true) {
      int? recommendationCircleId;
      String circleIds = selected!.map((e) {
        if (e.isRecommended) {
          recommendationCircleId = e.circle.id;
        }
        return e.circle.id;
      }).toList().join(',');
      Map<String, Object?> urls = {};
      if (mediaInfos.isNotEmpty == true) {
        MediaFileInfo fileInfo = mediaInfos[0];
        if (fileInfo.isVideo) {
          urls = {'video_ids': fileInfo.id};
        } else {
          urls = {'pic_ids': mediaInfos.map((e) => e.id).toList().join(',')};
        }
      }
      var data = {
        'type': widget.postType,
        'content': text,
        'circle_ids': circleIds,
        'recommend_circle_ids': recommendationCircleId
      };
      data.addAll(urls);
      sendReq(Api.publish(), BaseResp(), data: data);
    } else {
      Toast.show('请至少关联一个圈子');
    }
  }

  uploadImage(File image) async {
    final String path = image.path;
    final String filename = path.substring(path.lastIndexOf('/') + 1);
    var file = await MultipartFile.fromFile(path, filename: filename);
    debugPrint('file:${file.filename.toString()}');
    sendReq(Api.uploadPic(), UploadResp(), data: {'file': file});
  }

  uploadVideo(File video) async {
    final String path = video.path;
    final String filename = path.substring(path.lastIndexOf('/') + 1);
    var file = await MultipartFile.fromFile(path, filename: filename);
    sendReq(Api.uploadVideo(), UploadResp(), data: {'file': file});
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    print('ok111');
    if (t is UploadResp) {
      print('${t.data?.url}');
      if (t.data?.url != null) {
        mediaInfos.add(MediaFileInfo(t.data!.url!, t.data?.videoUrl?.isNotEmpty == true, t.data!.id));
        setState(() => {});
      }
    } else if (t is BaseResp) {
      if (t.code == 0) {
        contentController.text = '';
        AppNavigator.pop(context);
      }
      Toast.show(t.msg);
    }
  }
}

class MediaFileInfo {
  final String path;
  final bool isVideo;
  final int? id;

  MediaFileInfo(this.path, this.isVideo, this.id);
}